package cn.edu.zjut.mina.service.impl;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.edu.zjut.mina.bean.RoomInfo;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.interf.IRoomInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.service.INotificationService;
import cn.edu.zjut.mina.service.IUserShowCardsService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.UserSessionMap;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
@Service("userShowCardsService")
public class UserShowCardsServiceImpl implements IUserShowCardsService {

	/**
	 * 用于存放用户信息的集合
	 */
	private final UserSessionMap userSessionMap = UserSessionMap.getInstance();
	
	@Qualifier("notificationService")
	@Autowired
	private INotificationService notificationService;
	
	public JMessageProtocalRes showCards(StandardFormat inJson,
			IoSession session) {
		// TODO Auto-generated method stub
		System.out.println("execute --ShowCards()-- method.");
		
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		IRoomInfo roomInfo = userSessionMap.get(inJson.roomId);
		
		if (roomInfo == null) {//服务器异常
			System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "亮牌房间不存在：房间roomid=" + inJson.roomId);
			outJson.userId = inJson.userId;
			outJson.resultInfo = ResultInfoConstUtils.SHOWCARD_ROOMNULLINFO;
			outJson.result = false;
		}  else {
			synchronized(roomInfo) {
				
				//发来亮牌请求的客户端的showCard字段置1
				for (int index = 0; index < roomInfo.getActualParticipation(); index++) {
					if (roomInfo.getUserSessions().get(index).user.getUserId().equals(inJson.userId)) {
						roomInfo.setShowCardsNum(roomInfo.getShowCardsNum() + 1);
						roomInfo.getUserSessions().get(index).user.setShowCards(1);
						break;
					}
				}
				
				//通知所有人亮牌消息
				notificationService.notificationShowCards(inJson.roomId, inJson.userId);
				
				return null;
			}
			
		}
		//返回异常信息
		res.setResultCode(ProtocalRegulation.SHOWCARDSINITIATIVE);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}

}
